//
//  IFURLDocProtocol.m
//  IfengNews
//
//  Created by Ryan on 15/6/16.
//
//

#import "IFURLDocProtocol.h"
#import "SDWebImageManager.h"
#import "SDImageCache.h"

@interface IFURLDocProtocol()

@property (nonatomic,strong) NSURLConnection *connection;
@property (nonatomic,strong) NSMutableData *data;
@property (nonatomic,strong) NSURLResponse *response;
@property (nonatomic,strong) NSString *url;

@end

static NSObject *IFCachingSupportedSchemesMonitor;
static __weak NSSet *IFCachingSupportedSchemes;
static NSString *RNCachingURLHeader = @"X-RNCache";

@implementation IFURLDocProtocol

+ (void)initialize{
    if(self == [IFURLDocProtocol class]){
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            IFCachingSupportedSchemesMonitor = [NSObject new];
        });
        
       
    }
}

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    // only handle http requests we haven't marked with our header.
   
    if ([[self supportedSchemes] containsObject:[[request URL] absoluteString]] &&
       
        ([request valueForHTTPHeaderField:RNCachingURLHeader] == nil))
    {
        return YES;
    }
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

- (void)startLoading{
    
   
  
   UIImage *image =  [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[[SDWebImageManager sharedManager] cacheKeyForURL:[[self request] URL]]];
   
    if(image){
        NSData *data=UIImageJPEGRepresentation(image, 1.f);
        NSURLRequest *urlrequest=[self request].copy;
        NSURLResponse *response=[[NSURLResponse alloc] initWithURL:[urlrequest URL]
                                                          MIMEType:@"img"
                                             expectedContentLength:[data length]
                                                  textEncodingName:nil];
        [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        [[self client] URLProtocol:self didLoadData:data];
        [[self client] URLProtocolDidFinishLoading:self];

    }else{
        self.url=[[[self request] URL] absoluteString];
        NSMutableURLRequest *connectionRequest=[self request].mutableCopy;
        [connectionRequest setValue:@"" forHTTPHeaderField:RNCachingURLHeader];
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:connectionRequest
                                                                    delegate:self];
        [self setConnection:connection];

        
        
    }
    
    
}


// NSURLConnection delegates (generally we pass these on to our client)

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{

    if (response != nil) {
        NSMutableURLRequest *redirectableRequest =


        [request mutableCopy];

   
        [redirectableRequest setValue:nil forHTTPHeaderField:RNCachingURLHeader];
        

        [[self client] URLProtocol:self wasRedirectedToRequest:redirectableRequest redirectResponse:response];
        return redirectableRequest;
    } else {
        return request;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [[self client] URLProtocol:self didLoadData:data];
    [self appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[self client] URLProtocol:self didFailWithError:error];
    [self setConnection:nil];
    [self setData:nil];
    [self setResponse:nil];
    self.url=nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self setResponse:response];
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];  // We cache ourselves.
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [[self client] URLProtocolDidFinishLoading:self];
    
    if(self.data && [self.data length]>0)
    [[SDWebImageManager sharedManager] saveImageToCache:[UIImage imageWithData:self.data] forURL:[NSURL URLWithString:self.url]];
   
    
    [self setConnection:nil];
    [self setData:nil];
    [self setResponse:nil];
    self.url=nil;
}


- (void)appendData:(NSData *)newData
{
    if ([self data] == nil) {
        [self setData:[newData mutableCopy]];
    }
    else {
        [[self data] appendData:newData];
    }
}

- (void)stopLoading{
   [[self connection] cancel];
}


+ (void)setSupportedSchemes:(NSSet *)supportedSchemes
{
    @synchronized(IFCachingSupportedSchemesMonitor)
    {
        IFCachingSupportedSchemes = supportedSchemes;
    }
}

+ (NSSet *)supportedSchemes {
    NSSet *supportedSchemes;
    @synchronized(IFCachingSupportedSchemesMonitor)
    {
        supportedSchemes = IFCachingSupportedSchemes;
    }
    return supportedSchemes;
}

@end
